package com.minglead.springboot.platform.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.minglead.springboot.common.config.Global;
import com.minglead.springboot.common.crud.BaseController;
import com.minglead.springboot.common.persistence.Page;
import com.minglead.springboot.common.utils.StringUtils;
import com.minglead.springboot.platform.sys.entity.Office;
import com.minglead.springboot.platform.sys.entity.Role;
import com.minglead.springboot.platform.sys.entity.User;
import com.minglead.springboot.platform.sys.service.SystemService;
import com.minglead.springboot.platform.sys.utils.ActionResponse;
import com.minglead.springboot.platform.sys.utils.UserUtils;


@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}
	

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"index"})
	public String index(User user, Model model) {
		return "modules/sys/userIndex";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(String officeId, Model model) {
		User user=UserUtils.getUser();
		Role role=user.getRoleList().get(0);
		model.addAttribute("roleCode", role.getCode());
		model.addAttribute("officeId", officeId);
		return "modules/sys/userList";
	}
	@RequestMapping(value="loadData")
	public void loadData(String officeId,HttpServletRequest request, HttpServletResponse response){
		String name=request.getParameter("name");
		String loginName=request.getParameter("loginName");
		String officeNname=request.getParameter("officeNname");
		/***********封装查询条件begin******/
		User user=new User();
		user.setName(name);
		user.setLoginName(loginName);
		Office office=new Office();
		office.setName(officeNname);
		user.setOffice(office);
		/***********封装查询条件end******/
		if("1".equals(officeId)){
			officeId="";
		}
		if(StringUtils.isNotEmpty(officeId)){
			user.setOfficeId(officeId);
		}
		Page<User> page=new Page<User>(request,response);
		Page<User> userPage=systemService.findUser(page, user);
		renderGrid(request, response, userPage);
	}
	
	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"listData"})
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		return page;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("loginFlagList",User.getYesOrNoList());
		model.addAttribute("adminFlagList",User.getYesOrNoList());
		model.addAttribute("user", user);
		model.addAttribute("allRoles", systemService.findAllRole());
		return "modules/sys/userForm";
	}
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		user.setOffice(new Office(request.getParameter("office.id")));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			//解密
			String newPassword_0 = user.getNewPassword();
			user.setPassword(SystemService.entryptPassword(newPassword_0));
		}
		if (!beanValidator(model, user)){
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = new ArrayList<Role>();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()){
			if (roleIdList.contains(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
			UserUtils.clearCache();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + contextPath + adminPath + "/sys/user/list?repage";
	}
	
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public void delete(String id, HttpServletResponse response) {
		ActionResponse r = new ActionResponse(1,"操作成功！");
		if(StringUtils.isEmpty(id)){
			r.setMessage("删除失败,id不能为null");
			this.responseObject(r, response);
			return;
		}
		String[] _id = id.split(",");
		for(String id0:_id){
			User user=systemService.getUser(id0);
			systemService.deleteUser(user);
		}
		this.responseObject(r, response);
	}
	
	/**
	 * 验证登录名是否有效
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 用户信息显示及保存
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getName())){

			currentUser.setEmail(user.getEmail());
			currentUser.setPhone(user.getPhone());
			currentUser.setMobile(user.getMobile());
			currentUser.setRemarks(user.getRemarks());
			currentUser.setPhoto(user.getPhoto());
			systemService.updateUserInfo(currentUser);
			model.addAttribute("message", "保存用户信息成功");
		}
		model.addAttribute("user", currentUser);
		model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
	}

	/**
	 * 返回用户信息
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}
	
	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword,HttpServletRequest request,Model model) {
		
		//密码解密		
		String newPassword_ =  WebUtils.getCleanParam(request,"newPassword");
		String oldPassword_ =  WebUtils.getCleanParam(request,"oldPassword");
		
		newPassword = newPassword==null?null:StringUtils.uncompile(newPassword_);
		oldPassword = oldPassword==null?null:StringUtils.uncompile(oldPassword_);
		
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
/*			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userModifyPwd";
			}*/
			if (SystemService.validatePassword(oldPassword, user.getPassword())){
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String officeId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i=0; i<list.size(); i++){
			User e = list.get(i);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", "u_"+e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}
	/**
	 * 重置密码
	 * @param id
	 * @param loginName
	 * @param response
	 */
	@RequestMapping(value = { "resetPwd", "" })
	public void resetPwd(String id, String loginName, HttpServletResponse response) {
		ActionResponse r = new ActionResponse(1,"密码重置成功成功！<br/>新密码：123456");
		systemService.updatePasswordById(id, loginName, "123456");
		this.responseObject(r, response);
	}
	
}
